/**
 * 性能优化 Composable
 */
import { ref, computed, nextTick } from 'vue';
import { debounce, throttle } from 'lodash-es';

export function usePerformanceOptimization() {
  // 虚拟滚动配置
  const virtualScrollConfig = ref({
    enabled: false,
    itemHeight: 50,
    visibleCount: 20,
    bufferSize: 5,
  });

  // 启用虚拟滚动的阈值
  const VIRTUAL_SCROLL_THRESHOLD = 100;

  // 防抖搜索
  const debouncedSearch = debounce((searchFn: Function, ...args: any[]) => {
    searchFn(...args);
  }, 300);

  // 节流滚动
  const throttledScroll = throttle((scrollFn: Function, ...args: any[]) => {
    scrollFn(...args);
  }, 16); // 60fps

  // 批量更新优化
  const batchUpdateQueue = ref<Array<() => void>>([]);
  const isBatchUpdating = ref(false);

  // 批量执行更新
  async function flushBatchUpdates() {
    if (isBatchUpdating.value || batchUpdateQueue.value.length === 0) return;

    isBatchUpdating.value = true;
    
    try {
      // 等待下一个 tick 确保 DOM 更新完成
      await nextTick();
      
      // 批量执行所有更新
      const updates = [...batchUpdateQueue.value];
      batchUpdateQueue.value = [];
      
      updates.forEach(update => update());
    } finally {
      isBatchUpdating.value = false;
    }
  }

  // 添加到批量更新队列
  function addToBatchUpdate(updateFn: () => void) {
    batchUpdateQueue.value.push(updateFn);
    
    // 使用 requestAnimationFrame 确保在下一帧执行
    requestAnimationFrame(() => {
      flushBatchUpdates();
    });
  }

  // 内存优化：对象池
  const objectPool = new Map<string, any[]>();

  function getFromPool<T>(type: string, factory: () => T): T {
    if (!objectPool.has(type)) {
      objectPool.set(type, []);
    }
    
    const pool = objectPool.get(type)!;
    return pool.length > 0 ? pool.pop() : factory();
  }

  function returnToPool(type: string, obj: any) {
    if (!objectPool.has(type)) {
      objectPool.set(type, []);
    }
    
    const pool = objectPool.get(type)!;
    if (pool.length < 50) { // 限制池大小
      // 重置对象状态
      if (typeof obj === 'object' && obj !== null) {
        Object.keys(obj).forEach(key => {
          delete obj[key];
        });
      }
      pool.push(obj);
    }
  }

  // 智能深拷贝：根据数据大小选择策略
  function smartClone<T>(data: T): T {
    if (data === null || data === undefined) return data;
    
    // 基本类型直接返回
    if (typeof data !== 'object') return data;
    
    // 数组处理
    if (Array.isArray(data)) {
      if (data.length < 100) {
        // 小数组使用 JSON 方式
        return JSON.parse(JSON.stringify(data));
      } else {
        // 大数组使用浅拷贝 + 递归
        return data.map(item => smartClone(item)) as T;
      }
    }
    
    // 对象处理
    const keys = Object.keys(data);
    if (keys.length < 20) {
      // 小对象使用 JSON 方式
      try {
        return JSON.parse(JSON.stringify(data));
      } catch {
        // JSON 序列化失败时使用手动拷贝
        return manualClone(data);
      }
    } else {
      // 大对象使用手动拷贝
      return manualClone(data);
    }
  }

  function manualClone<T>(obj: T): T {
    if (obj === null || typeof obj !== 'object') return obj;
    
    if (obj instanceof Date) return new Date(obj.getTime()) as T;
    if (obj instanceof Array) return obj.map(item => manualClone(item)) as T;
    
    const cloned = {} as T;
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        cloned[key] = manualClone(obj[key]);
      }
    }
    return cloned;
  }

  // 内存监控
  const memoryUsage = ref({
    used: 0,
    total: 0,
    percentage: 0,
  });

  function updateMemoryUsage() {
    if ('memory' in performance) {
      const memory = (performance as any).memory;
      memoryUsage.value = {
        used: Math.round(memory.usedJSHeapSize / 1024 / 1024),
        total: Math.round(memory.totalJSHeapSize / 1024 / 1024),
        percentage: Math.round((memory.usedJSHeapSize / memory.jsHeapSizeLimit) * 100),
      };
    }
  }

  // 定期更新内存使用情况
  const memoryMonitorInterval = setInterval(updateMemoryUsage, 5000);

  // 清理函数
  function cleanup() {
    clearInterval(memoryMonitorInterval);
    objectPool.clear();
    batchUpdateQueue.value = [];
  }

  // 性能指标
  const performanceMetrics = ref({
    renderTime: 0,
    updateTime: 0,
    memoryUsage: 0,
  });

  // 性能测量
  function measurePerformance<T>(name: string, fn: () => T): T {
    const start = performance.now();
    const result = fn();
    const end = performance.now();
    
    console.log(`${name} 执行时间: ${(end - start).toFixed(2)}ms`);
    
    if (name.includes('render')) {
      performanceMetrics.value.renderTime = end - start;
    } else if (name.includes('update')) {
      performanceMetrics.value.updateTime = end - start;
    }
    
    return result;
  }

  // 异步性能测量
  async function measureAsyncPerformance<T>(name: string, fn: () => Promise<T>): Promise<T> {
    const start = performance.now();
    const result = await fn();
    const end = performance.now();
    
    console.log(`${name} 执行时间: ${(end - start).toFixed(2)}ms`);
    return result;
  }

  return {
    // 虚拟滚动
    virtualScrollConfig,
    VIRTUAL_SCROLL_THRESHOLD,
    
    // 防抖节流
    debouncedSearch,
    throttledScroll,
    
    // 批量更新
    addToBatchUpdate,
    flushBatchUpdates,
    
    // 对象池
    getFromPool,
    returnToPool,
    
    // 智能克隆
    smartClone,
    
    // 内存监控
    memoryUsage,
    updateMemoryUsage,
    
    // 性能测量
    performanceMetrics,
    measurePerformance,
    measureAsyncPerformance,
    
    // 清理
    cleanup,
  };
}
